#include "pcscreen.h"

#include <QRandomGenerator>
#include <QDateTime>
#include <QDebug>
#include <QThread>

const QString COMMON = "kylin-screencast.AppImage";

PCScreen::PCScreen(QObject *parent) : QObject(parent) {}

PCScreen::~PCScreen()
{
    if (m_process != nullptr) {
        if (m_process->state() == QProcess::Running) {
            qInfo() << "Exiting screen projection service...";
            m_process->close();
        }
        delete m_process;
        m_process = nullptr;
    }
}

void PCScreen::startService()
{
    qInfo() << "Starting projection service...";
    if (m_process == nullptr) {
        m_process = new QProcess(this);
        isNormalExit = false;
        connect(m_process, &QProcess::started, this, [=]() {
            qInfo() << "Screen projection service started successfully!";
            QThread::msleep(8000);
            Q_EMIT sigStartedScreen(m_roomid);
        });
        // connect(m_process, &QProcess::errorOccurred, [&](QProcess::ProcessError error) {
        //     if (!isNormalExit) {
        //         qInfo() << "Screen projection service error:" << error;
        //         Q_EMIT sigStartError();
        //     }
        // });
        getRoomId();
        m_process->start(COMMON, QStringList() << m_roomid);
    } else {
        qInfo() << "Currently, there are screen projection services";
    }
}

void PCScreen::getRoomId()
{
    int min = 99999;
    int max = 1000000;
    //种子
    quint32 seed = quint32(QDateTime::currentDateTime().toSecsSinceEpoch());
    QRandomGenerator generator(seed);
    int rand = generator.bounded(min, max);
    m_roomid = QString::number(rand);
    if (m_roomid.isEmpty()) {
        m_roomid = "123456";
    }
    qInfo() << "The random ID generated by the screen projection device is " << m_roomid;
    return;
}